package finelProject.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import com.google.gson.Gson;

import example.AppConstants;
import finelProject.MyAppConstants;
import finelProject.model.User;

/**
 * Servlet implementation class ReturnUsersWhoIFollow
 */
public class ReturnUsersWhoIFollow extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReturnUsersWhoIFollow() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try{
			//obtain UserDB data source from Tomcat's context
			Context context = new InitialContext();
			BasicDataSource ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
			Connection conn = ds.getConnection();

			Collection<User> usersResult = new ArrayList<User>();
			
			//get the current user's Username
			String Username = (String) request.getSession().getAttribute("Username");
			
			try {
				//searching for all the users who the current user follow
				PreparedStatement stmt;
				stmt = conn.prepareStatement(MyAppConstants.SELECT_WHO_USER_FOLLOWS);
				stmt.setString	 (1, Username);
			
				//return users instances of the users who the current user follow.
				ResultSet rs = stmt.executeQuery();
			
				//this loop will go over all the users who the current user follows
				while (rs.next()){
					//adds the returned user in to the result array.
					usersResult.add(new User(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5)));
				}
			
				rs.close();
				stmt.close();
				
			} catch (SQLException e) {
				getServletContext().log("Error while querying for customers", e);
	    		response.sendError(500);//internal server error
			}
			conn.close();
			
			Gson gson = new Gson();
        	//convert from Users collection to json
        	String UserJsonResult = gson.toJson(usersResult, MyAppConstants.USER_COLLECTION);

        	PrintWriter writer = response.getWriter();
        	writer.println(UserJsonResult);
        	writer.close();
		
		}catch(SQLException | NamingException e){
			getServletContext().log("Error while closing connection", e);
    		response.sendError(500);//internal server error
		}
	}

}
